package com.zhongkun.datahome.framework.web.service;

import com.zhongkun.datahome.common.core.domain.entity.SysUser;
import com.zhongkun.datahome.common.core.domain.entity.TenantUser;
import com.zhongkun.datahome.common.core.domain.model.LoginUser;
import com.zhongkun.datahome.common.exception.ServiceException;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import com.zhongkun.datahome.core.service.ISysRoleService;
import com.zhongkun.datahome.core.service.ISysUserService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class WeixinUserDetailsService implements UserDetailsService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService sysRoleService;

    // 默认方法（支持用户名/手机号登录）
    @Override
    public UserDetails loadUserByUsername(String username) {
        return null;
    }

    // 新增方法：基于 openid 加载或创建用户
    public UserDetails loadByMobile(String mobile) {
        SysUser user = userService.selectUserByPhone(mobile);
        if (user == null) {
            throw new ServiceException("手机号未在系统内注册，请联系管理员");
        }
        user.setRoles(sysRoleService.queryRolesByUserId(user.getUserId()));
        return new LoginUser(user.getUserId(), user.getDeptId(), user, null, new TenantUser(user.getTenantUserId(), user.getUserId(), SecurityUtils.getTenantId()));
    }
}